package com.up.upzl.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.up.upzl.base.service.impl.BaseServiceImpl;
import com.up.upzl.biz.domain.Module;
import com.up.upzl.biz.domain.Module.PageType;
import com.up.upzl.biz.domain.Module.ShowType;
import com.up.upzl.biz.repository.ModuleRepository;
import com.up.upzl.biz.service.ModuleService;

@Service
public class ModuleServiceImpl extends BaseServiceImpl<Module, Long> implements ModuleService {

	@Autowired
	private ModuleRepository moduleRepository;

	@Override
	public Page<Module> findByCondition(PageType pageType, ShowType showType, String name, Pageable page) {
		return moduleRepository.findAll(new Specification<Module>() {

			@Override
			public Predicate toPredicate(Root<Module> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(name)) {
					predicates.add(cb.and(cb.like(root.get("name"), "%" + name + "%")));
				}
				if (!StringUtils.isEmpty(pageType)) {
					predicates.add(cb.and(cb.equal(root.get("pageType"), pageType)));
				}
				if (!StringUtils.isEmpty(showType)) {
					predicates.add(cb.and(cb.equal(root.get("showType"), showType)));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}

	/**
	 * 根据模块展示类型和板块类型获取模块的详细信息
	 * 
	 * @param showType
	 *            模块展示类型 * @param pageType 所属板块类型
	 * 
	 * @return 模块的信息
	 */
	@Override

	public List<Module> findByShowTypeAndPageType(ShowType showType, PageType pageType) {
		return moduleRepository.findAll(new Specification<Module>() {

			@Override
			public Predicate toPredicate(Root<Module> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(pageType)) {
					predicates.add(cb.and(cb.equal(root.get("pageType"), pageType)));
				}
				if (!StringUtils.isEmpty(showType)) {
					predicates.add(cb.and(cb.equal(root.get("showType"), showType)));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, new Sort(Direction.DESC, "sort"));
	}

}
